import { type BrowserWindow, dialog, ipcMain } from 'electron';
import fs from 'node:fs';
import * as os from 'node:os';
import path from 'node:path';
import readline from 'node:readline';

import { CodeTableConverter, DEFAULT_CONFIG_PATH } from './Tools';
import { ICodeTableData } from './types';

/** 读取目录中以.dict.yaml结尾的文件 */
async function fetchDirectory(mainWindow: BrowserWindow, isDefault: boolean): Promise<{
  fileName: string;
  fileFullPath: string;
}[]> {
  let directoryPath: string;
  if (isDefault) {
    directoryPath = DEFAULT_CONFIG_PATH;
  }
  else {
    const {
      canceled,
      filePaths
    } = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory']
    }); // 目录选择器
    if (canceled) {
      return [];
    }
    directoryPath = filePaths[0];
  }
  // directoryPath = '/Volumes/Data/Code/测试';
  // 向渲染进程发送事件
  return fs
    .readdirSync(directoryPath)
    .filter((filePath) => filePath.endsWith('.dict.yaml'))
    .map((file) => {
      const fileFullPath = path.join(directoryPath, file);
      // 提取文件名：不含.dict.yaml后缀
      const fileName = (fileFullPath.split('/').pop() || '').split('.dict.yaml')[0];
      return {
        fileName,
        fileFullPath
      };
    });
}


/** 读取字典文件 */
function fetchDict(filePath: string): Promise<ICodeTableData> {
  return new Promise((resolve, reject) => {
    // 创建 readline 接口实例
    const rl = readline.createInterface({
      input: fs.createReadStream(filePath),
      crlfDelay: Number.POSITIVE_INFINITY // 用于设置将\r\n识别为单个换行符的延迟时间，即如果是\r\n，会被识别为一个换行符
    });

    const converter = new CodeTableConverter(filePath);

    // 按行读取文件
    rl.on('line', (line) => {
      converter.converterLine(line);
    });

    // 文件读取完成
    rl.on('close', () => {
      resolve(converter.codeTableData); // 返回解析后的数据
    });

    // 处理错误
    rl.on('error', (err) => {
      reject(err); // 抛出错误
    });
  });
}


/** 流式写入版本（适合大型数组） */
function saveDict(filePath: string, lines: string[]): Promise<void> {
  return new Promise((resolve, reject) => {
    const writer = fs.createWriteStream(filePath, 'utf8');
    console.log(lines);
    const eol = os.EOL;
    writer.on('finish', resolve);
    writer.on('error', reject);

    // 遍历每行内容，统计---字符出现次数，若为偶数次就将其替换成...
    let dashCount = 0;
    const newLines = lines.map((line) => {
      const count = (line.match(/---/g) || []).length;
      dashCount += count;
      if (dashCount % 2 === 0) {
        return line.replace(/---/g, '...');
      }
      return line;
    });
    // 精确控制换行符
    newLines.forEach((line, index) => {
      const isLastLine = index === lines.length - 1;
      writer.write(line + (isLastLine ? '' : eol));
    });

    writer.end();
  });
}


export function ipcManager(mainWindow: BrowserWindow) {
  // 读取Rime配置目录
  ipcMain.handle('fetch-directory', (_, isDefault: boolean) => {
    return fetchDirectory(mainWindow, isDefault);
  });
  // 读取Rime字典
  ipcMain.handle('fetch-dict', (_, filePath: string) => {
    return fetchDict(filePath);
  });
  // 保存Rime字典
  ipcMain.handle('save-dict', (_, filePath: string, lines: string[]) => {
    return saveDict(filePath, lines);
  });
}
